package com.urchin.avatarhero.questview;

import java.util.ArrayList;

import android.database.Cursor;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

import com.urchin.avatarhero.R;
import com.urchin.avatarhero.util.SQLiteHandler;
import com.urchin.avatarhero.util.Utilities;
import com.urchin.avatarhero.util.cal.CalBlob;
import com.urchin.avatarhero.util.cal.CalendarHandler;

/**********************************************************************
AvatarHero - A task management RPG Android Application
Copyright (C) 2013  Peter Clay

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://www.gnu.org/licenses/>.
***********************************************************************/

public class AvailableQuests extends QuestView {
	private ArrayList<String> elist = new ArrayList<String>();
	private ArrayList<CalBlob> datalist = new ArrayList<CalBlob>();
	private int listpos = 0;
		 
	@Override
	public void refresh() {
		
		// Set the Header Text
	     TextView textViewHeader = (TextView) findViewById(R.id.questHeader);
		 textViewHeader.setText(R.string.title_activity_AvailableQuests);
	     
		 elist.clear();
		 build_elist();

		 // Create the adapter
	     if(this.qadapter == null) {
			 this.qadapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, elist);
		     listView = (ListView) findViewById(R.id.questButtons);
		     listView.setAdapter(this.qadapter);
		     listView.setOnItemClickListener(QuestClickedHandler);
		     listView.setSelection(listpos);
	     } else {	     
	    	 this.qadapter.notifyDataSetChanged();
	     }
	     
	}
	
	public void build_elist() {
		// Display the list of available quests
	     // Get the Calendar data
	     CalendarHandler calhandle = new CalendarHandler(this);
	     // Get the Event and Instance data
	     ArrayList<CalBlob> cdata = calhandle.buildCalData(calhandle.getEvents(), calhandle.getInstances());
	     Utilities util = new Utilities(this);
	     
	     SQLiteHandler dbHandler = new SQLiteHandler(getApplicationContext());
		 dbHandler.opendb();
		 Cursor rcursor = dbHandler.getAllQuests();			// Flip this to get the available quests (i.e. not quests yet)
		
		//Toast.makeText(getApplicationContext(),"Len: " + String.valueOf(rcursor.getCount()),Toast.LENGTH_SHORT).show();

	     // Remove any entries with exp already assigned
		 int found = 0;
		 int count = 0;
		 for(int i=0;i<cdata.size();i++) {
	    	 found = 0;
			 rcursor.moveToFirst();							// Move back to the beginning
			 for(int j=0;j<rcursor.getCount();j++) {
	    		 if( String.valueOf(cdata.get(i).getInstanceid()).equals(rcursor.getString(2)) && 
	    				 String.valueOf(cdata.get(i).getEventid()).equals(rcursor.getString(1))) {		// Event and Instance match, don't display as available
	    			found = 1;
	    		 }
	    		 rcursor.moveToNext();
	    	 }
	    	 if(found == 0) {
	    		 datalist.add(cdata.get(i));				// Add to the datalist
	    		 elist.add(util.convertToStrPattern(cdata.get(i), "caldisp",dbHandler));		// Convert to the calendar display pattern
	    	 }
	    	 count++;
	     }
	     
	     rcursor.close();
		 dbHandler.closedb();
		 
		 // Find the most recent quest by date
		 listpos = util.findPosRecentDateQuest(datalist);
		Toast.makeText(getApplicationContext(),"Pos: " + String.valueOf(listpos),Toast.LENGTH_SHORT).show();

	}
	 
	 private OnItemClickListener QuestClickedHandler = new OnItemClickListener() {
		 public void onItemClick(AdapterView parent, View v, int position, long id)
		 {
			 Utilities util = new Utilities(act);
			// Display a messagebox.
			 String calstuff = (String) ((TextView)v).getText();
			 CalBlob cb = util.StrPatternToCalBlob(calstuff);
			 			 
			 // Find the actual instance
			 CalendarHandler calhandle = new CalendarHandler(act);
		     ArrayList<CalBlob> cdata = calhandle.buildCalData(calhandle.getEvents(), calhandle.getInstances());
		     for(CalBlob instance : cdata) {
		    	 if((cb.getStarttime() == instance.getStarttime()) && (cb.getTitle().equals(instance.getTitle()))) {		// If the begin times match up and the names match
		    		 cb.setCalid(instance.getCalid());
		    		 cb.setInstanceid(instance.getInstanceid());
		    		 cb.setEventid(instance.getEventid());
		    		 break;
		    	 }		  	  	 
		     }
		     
		     // Create and show the dialog
		     mStackLevel++;

		     FragmentTransaction ft = act.getSupportFragmentManager().beginTransaction();
		     Fragment prev = act.getSupportFragmentManager().findFragmentByTag("aqd");
		     if (prev != null) {
		    	 ft.remove(prev);
		     }
		     ft.addToBackStack(null);
		     ft.commit();
		 
		     AvailQuestDialog newFragment = AvailQuestDialog.newInstance(mStackLevel, cb.getCalid(), cb.getEventid(), cb.getInstanceid(), AvailableQuests.this.qadapter, AvailableQuests.this.act);
		     newFragment.show(act.getSupportFragmentManager(), "aqd");
		 }
	 };
}
